package forms;

import java.util.Map;
import java.util.TreeMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import com.google.appengine.api.blobstore.BlobInfo;
import com.google.appengine.api.blobstore.BlobInfoFactory;
import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;

import entities.User;

public class UserForm {
	public static TreeMap checkValid(HttpServletRequest request, User user) {
		TreeMap form = new TreeMap();
		TreeMap check = new TreeMap();
		
		String name = (String) request.getParameter("name");
		String gender = (String) request.getParameter("gender");
		
		if (name == null || name.equals("")) {
			check.put("name", "Full name is not empty");
			user.setName("");
		} else {
			user.setName(name);
		}
		
		if (gender != null) {
			try {
				user.setGender(Integer.parseInt(gender));
			} catch (Exception e) {
				check.put("gender", "Gender for user not valid!");
			}
		}
		
		form.put("checkValid", check);
		form.put("user", user);
		
		return form;
	}
	
	public static TreeMap checkValidAvatar(HttpServletRequest request, User user) {
		TreeMap form = new TreeMap();
		TreeMap check = new TreeMap();
		
		BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
		
		//Check avatar
		Map<String, BlobKey> blobs = blobstoreService.getUploadedBlobs(request);
	    BlobKey blobKey = blobs.get("avatar");
	    
	    if (blobKey != null && check.size() == 0) {
	    	
	    	BlobInfo info = new BlobInfoFactory().loadBlobInfo(blobKey);
	    	//Check is image
	    	if (!checkImage(info.getFilename())) {
	    		blobstoreService.delete(blobKey);
	    		check.put("avatar", "File is not a image.");
	    	} else {
	    		//Delete old
		    	if (user.getAvatar()!= null && !user.getAvatar().isEmpty()) {
		    		BlobKey blobKeyOld = new BlobKey(user.getAvatar());
		    		try {
		    			blobstoreService.delete(blobKeyOld);
					} catch (Exception e) {
					}
		    		
		    	}
		    	user.setAvatar(blobKey.getKeyString());
	    	}
	    } else if (blobKey != null) {
	    	blobstoreService.delete(blobKey);
		}
		
		form.put("checkValid", check);
		form.put("user", user);

		return form;
	}
	
	private static boolean checkImage(String name) {
		boolean valid = false;
		
		Pattern pattern = Pattern.compile("([^\\s]+(\\.(?i)(jpg|png|gif|bmp))$)");
		Matcher matcher = pattern.matcher(name);
		
		return matcher.matches();
	}
}
